TESTS = \
  tests/lexer/test-lexer.sh \
  tests/parser/test-parser.sh \
  tests/interpreter/test-interpreter.sh \
  tests/generator/test-generator.sh \
  tests/vm/test-vm.sh \
  $(EMPTY)

PROGS = \
  lexer \
  parser \
  interpreter \
  generator \
  vm \
  $(EMPTY)

all: $(PROGS)

V ?= 0
_AT_1 =
_AT_0 = @
_AT = $(_AT_$(V))
_IMG_1 =
_IMG_0 = @echo "  IMG     " $@;
_IMG = $(_IMG_$(V))

no_redefines = sed 's/redefined [^ ]*\( with [^ ]*\)\?  *//g'

_P_COUNT = 0
ifndef _P_TOTAL
_P_MARK := ++progress-mark++
_P_TOTAL := $(shell $(MAKE) -n _P_TOTAL=$(_P_MARK) $(MAKECMDGOALS) | grep --count -F -- $(_P_MARK))
endif
PROGRESS_PERCENT ?= yes
ifeq ($(PROGRESS_PERCENT),yes)
  _P = $(eval _P_COUNT = $(shell expr $(_P_COUNT) + 1)) printf "[%3d%%] " `expr \( $(_P_COUNT) \* 100 \) \/ $(_P_TOTAL)`
else
  _P_WIDTH := $(shell printf "$(_P_TOTAL)" | wc -c)
  _P = $(eval _P_COUNT = $(shell expr $(_P_COUNT) + 1)) printf "[%$(_P_WIDTH)d/$(_P_TOTAL)] " $(_P_COUNT);
endif

# Image generation in gforthmi manipulates temporary files whose names
# are not unique, so we cannot build images in parallel.
.NOTPARALLEL:
$(PROGS): %: %.fs
	@$(_P)
	$(_IMG)gforthmi $@ $< 3>&1 1>/dev/null 2>&3 3>&1 | $(no_redefines) >&2

check: $(TESTS) $(PROGS)
	$(_AT)srcdir=`pwd`; \
	for t in $(TESTS); do \
	  printf "%40s : " $$t; \
	  srcdir=$$srcdir $$t; \
	  case $$? in \
	    0) printf "\033[32mPASS\033[0m\n" ;; \
	    77) printf "\033[34mSKIP\033[0m\n" ;; \
	    *) printf "\033[31mFAIL\033[0m\n" ;; \
	  esac; \
	done

clean:
	rm -f test-*.tmp test-*.log $(PROGS)
